package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VoiceApiImpl implements VoiceApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String save(Voice voice) {
        //1、设置属性
        voice.setCreated(System.currentTimeMillis());
        //2、调用方法保存对象
        mongoTemplate.save(voice);
        //3、返回对象id
        return voice.toString();
    }

    @Override
    public Voice randomVoice() {
        Criteria criteria = Criteria.where("alreadRead").is(false);
        //1、创建统计对象，设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(
                Voice.class,
                //先进行条件筛选,一定要注意顺序（筛选与_class无关）
                Aggregation.match(criteria),
                //再进行随机取值
                Aggregation.sample(1)
        );
        //2、调用mongoTemplate方法统计
        AggregationResults<Voice> results = mongoTemplate.aggregate(aggregation, Voice.class);
        List<Voice> mappedResults = results.getMappedResults();
        if(CollUtil.isEmpty(mappedResults)){
            return null;
        }
        return mappedResults.get(0);
    }

    @Override
    public void updateState(String id, boolean state) {
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id)));
        Update update = Update.update("alreadRead",state);
        this.mongoTemplate.updateFirst(query,update,Voice.class);
    }
}
